﻿using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using System.Data;
using System.Text;

namespace Himp.TaskScheduling
{
    /// <summary>
    /// 自动审核标准化验任务
    /// </summary>
    public class AuditStandardTestTaskWorker : IHostedService
    {
        #region SQL

        public const string GET_STANDARD_TEST_TASK_SQL = @"
            SELECT *
            FROM [TaskScheduling].[TS_StandardTestTasks]
            WHERE ExecStas = N'未就绪'
            ";

        public const string UPDATE_STANDARD_TEST_TASK_SQL = @"
            UPDATE
            [TaskScheduling].[TS_StandardTestTasks]
            SET ExecStas = N'已审核'
            WHERE ID=@ID
            ";

        public const string INSERT_STANDARD_TEST_TASK_SQL = @"
            INSERT INTO
            [TaskScheduling].[TS_SampleTestTasks]
            (
            SampleCode,
            TestCode,
            BottomCode,
            Sampletype,
            TestCnt,
            TaskAssgnTime,
            LastOperTime,
            TestItems,
            ExecStas,
            ManualFlag
            )
            VALUES
            (
            @SampleCode,
            @TestCode,
            @BottomCode,
            @Sampletype,
            @TestCnt,
            GETDATE(),
            GETDATE(),
            @TestItems,
            @ExecStas,
            @ManualFlag
            )
            ";

        public const string EXIST_STANDARD_TEST_TASK_CH_SQL = @"
            SELECT COUNT(*)
            FROM [TaskScheduling].[TS_SampleTestTasks]
            WHERE TestItems = 'CHN,Mad,A,V,Q,S' AND CONVERT(VARCHAR(10), TaskAssgnTime, 120) = CONVERT(VARCHAR(10), GETDATE(), 120)
            ";

        #endregion

        #region 字段

        private readonly ILogger<AuditStandardTestTaskWorker> _logger;
        private readonly ConnectionStringOption _connectionStrings;

        #endregion

        #region 方法

        public AuditStandardTestTaskWorker(ILogger<AuditStandardTestTaskWorker> logger
            ,IOptions<ConnectionStringOption> connectionStrings)
        {
            _logger = logger;
            _connectionStrings = connectionStrings.Value;
        }

        /// <summary>
        /// 标准
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("--------自动审核标准化验任务开始启动--------");

            try
            {
                using (IDbConnection connection = new SqlConnection(_connectionStrings.RL_Web))
                {
                    connection.Open();
                    // 读取数据
                    var standardTestTaskResultList = connection.Query<StandardTestTask>(GET_STANDARD_TEST_TASK_SQL);

                    foreach (var item in standardTestTaskResultList)
                    {
                        var testItems = "";
                        var chnCount = connection.QuerySingle<int>(EXIST_STANDARD_TEST_TASK_CH_SQL);

                        if (item.Sampletype == "21")
                        {
                            testItems = "Mad,A,V,Q,S";

                            if (chnCount < 2) 
                            {
                                testItems = "CHN,Mad,A,V,Q,S";
                            }
                        }
                        else if (item.Sampletype == "61")
                        {
                            testItems = "Mt";
                            continue;
                        }

                        SampleTestTask sampleTestTask = new SampleTestTask(item.SampleCode
                            , item.TestCode
                            , item.BottomCode
                            , item.Sampletype
                            , item.TestCnt
                            , testItems
                            , 0);

                        var insertStas = await connection.ExecuteAsync(INSERT_STANDARD_TEST_TASK_SQL, sampleTestTask);
                        var updateStas = await connection.ExecuteAsync(UPDATE_STANDARD_TEST_TASK_SQL, new { ID = item.Id });
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("异常");
                Console.WriteLine(e.Message);
            }

            _logger.LogInformation("--------自动审核标准化验任务完成--------");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        #endregion
    }
}
